package com.rui.sideup.module.easyexcel.service;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import com.rui.sideup.module.easyexcel.entity.RowRange;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;
import java.util.Map;

/**
 * 合并类
 */
public class MergeStrategy extends AbstractMergeStrategy {

    // Map<列， 要进行合并的行>
    private Map<String, List<RowRange>> strategyMap;

    public MergeStrategy(Map<String, List<RowRange>> strategyMap) {
        this.strategyMap = strategyMap;
    }

    /**
     * 每一个单元格都会进入到该方法
     * 第一个单元格进入到该方法时就进行合并操作，其余单元格进入到该方法时不进行合并操作
     */
    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {

        int rowIndex = cell.getRowIndex();
        int columnIndex1 = cell.getColumnIndex();

        if (rowIndex == 1 && columnIndex1 == 0) {
            for (Map.Entry<String, List<RowRange>> entry : strategyMap.entrySet()) {
                // 哪一列的行需要进行合并
                int columnIndex = Integer.parseInt(entry.getKey());
                entry.getValue().forEach(rowRange -> {
                    // 对行进行合并(四个参数: 行开始 行结束 列开始 列结束)
                    sheet.addMergedRegionUnsafe(new CellRangeAddress(rowRange.getStart(), rowRange.getEnd(), columnIndex, columnIndex));
                });
            }
        }

    }
}
